<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>权限管理</title>
<%--<%@include file="/WEB-INF/views/header.jsp"%>  --%>
<link rel="stylesheet"
	href="${basePath}/static/plugins/bootstrap-table/bootstrap-table.min.css">
<link rel="stylesheet"
	href="${basePath}/static/plugins/iCheck/custom.css">
<link rel="stylesheet"
	href="${basePath}/static/plugins/datatables/dataTables.bootstrap.css">
<link rel="stylesheet"
	href="${basePath}/static/plugins/layer/skin/layer.css">
<link rel="stylesheet"
	href="${basePath}/static/plugins/select2/select2.css">	
</head>
<body class="hold-transition skin-blue fixed sidebar-mini">
	<!-- 右边内容区域  -->
	<section class="content-header">
		<ol class="breadcrumb">
			<li><a href="${basePath }/sys/role"><i class="fa fa-dashboard"></i> 系统设置</a></li>
			<li class="active">角色管理</li>
		</ol>
	</section>

	<div class="content">
		<div class="row">
			<div class="col-md-3">
				<a href="javascrpit:void(0)"
					class="btn btn-primary btn-block margin-bottom  add-role">新增角色</a>

				<div class="box box-solid">
					<div class="box-header with-border">
						<h3 class="box-title">角色列表</h3>

						<div class="box-tools">
							<button type="button" class="btn btn-box-tool" data-widget="collapse">
								<i class="fa fa-minus"></i>
							</button>
						</div>
					</div>
					<div class="box-body no-padding">
						<ul class="nav nav-pills nav-stacked role-list">
							
						</ul>
					</div>
					<!-- /.box-body -->
				</div>
			</div>
			<div class="col-md-9">
				<div class="nav-tabs-custom" style="min-height: 750px">
					<!-- Tabs within a box -->
					<ul class="nav nav-tabs ui-sortable-handle">
						<li class="active"><a href="#user-role" data-toggle="tab">用户授权</a></li>
						<li><a href="#resource-role" data-toggle="tab">资源授权</a></li>
					</ul>
					<div class="tab-content no-padding">
						<!-- Morris chart - Sales -->
						<div class="tab-pane active" id="user-role">
							<div class="row" style="margin-top:20px">
								<div class="col-sm-6" style="padding-left:30px;">
							    	<div class="form-group">
							      		<select id="sel_menu2" multiple="multiple" class="form-control" >
							      		</select>
								 	</div>
					      		</div>
					      		<div class="col-sm-2">
					      			<a href="javascript:void(0)" class="btn btn-warning saveUserRoleBtn" style="width:120px;">添加</a>
				      			</div>
				      		</div>
				      		<div class="full-height-scroll">
								<div class="content">
									<table id="role_user_grid"
										class="table table-bordered table-hover">
										<thead>
											<tr>
												<th class="text-center"><input type="checkbox"
													class="checkall" /></th>
												<th>姓名</th>
												<th>部门</th>
												<th>电话</th>
												<th class="text-center">操作</th>
											</tr>
										</thead>
									</table>
								</div>
							</div>
						</div>
						<div class="tab-pane" id="resource-role">
							<section class="content margin">
								<div class="row m-b-10">
									<label class="col-sm-2 control-label">角色权限明细</label>
									<div class="col-sm-2">
										<label class="checkbox-inline i-checks" /> <input type="checkbox" value="option1">全选
									</div>
								</div>
							</section>
						</div>
					</div>

				<!--</div>-->
				</div>
			</div>
		</div>
	</div>
	<div class="modal fade" id="role_modal" tabindex="-1" role="dialog">
		<form id="role_from">
			<div class="modal-dialog">
				<div class="modal-content">
					<div class="modal-body  no-padding">
						<div class="box box-primary">
							<div class="box-header with-border">
								<h3 class="box-title">新增角色</h3>
							</div>

							<div class="box-body">
								<div class="form-group">
									<label for="exampleInputEmail1">角色名称</label> <input type="text"
										class="form-control" name="roleName" placeholder="请输入角色名称">
								</div>
								<div class="form-group">
									<label for="exampleInputPassword1">角色描述</label> <input
										type="text" class="form-control" name="roleDesc"
										placeholder="请输入角色描述">
								</div>
							</div>
						</div>
					</div>
					<div class="modal-footer">
						<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						<button type="submit" class="btn btn-primary">保存</button>
					</div>
				</div>
			</div>
		</form>
	</div>
	<!-- ./wrapper -->

	<%--<%@include file="/WEB-INF/views/footer.jsp"%> --%>
	<script type="text/javascript"
		src="${basePath}/static/plugins/bootstrap-table/bootstrap-table.min.js"></script>
	<script type="text/javascript"
		src="${basePath}/static/plugins/bootstrap-table/bootstrap-table-locale-all.min.js"></script>
	<script type="text/javascript"
		src="${basePath}/static/plugins/iCheck/icheck.min.js"></script>
	<script type="text/javascript"
		src="${basePath}/static/plugins/layer/layer.min.js"></script>
	<script type="text/javascript"
		src="${basePath}/static/plugins/jquery.validate/jquery.validate.min.js"></script>
	<script src="${basePath}/static/plugins/datatables/jquery.dataTables.js"></script>
	<script src="${basePath}/static/plugins/datatables/dataTables.bootstrap.js"></script>
	<script type="text/javascript" src="${basePath}/static/plugins/select2/select2.js"></script>
	<script type="text/javascript" src="${basePath}/static/plugins/select2/i18n/zh-CN.js"></script>
	<script>
		$(document).ready(function() {
			
			// 用户查询初始化
			jQuery("#sel_menu2").select2({
				placeholder: "请输入成员姓名",
				ajax: {
					url: basePath + "/org/getUsers",
					dataType: 'json',
					delay: 250,
					data: function (params) {
						//console.log(params)
						return {
							q: params.term, // search term
							page: params.page || 0
						};
					},
					processResults: function (json, params) {
						console.log(json);
						console.log(params);
						params.page = params.page || 0;
						var list = json.data.pagerList;
						var resultList = [];
						for (var int = 0; int < list.length; int++) {
							var array_element = list[int];
							var obj = {
								"id" : array_element.eId,
								"text" : array_element.EmpName
							}
							resultList.push(obj);
							
						} 
						return {
							results: resultList,
							pagination: {
								more: (params.page * 20) < json.data.totalRow
							}
						};
					},
					cache: false
				},
				language: "zh-CN"
			});
			
			// 添加用户授权
			jQuery("a.saveUserRoleBtn").on('click', function (e) {
				var $this = jQuery(this);
				var roleId = $this.data('roleid');
				// console.log(labelsId);
				if (!roleId) {
					swal("系统提示", "请先选择一个角色后才能进行添加操作", "warning");
					return false;
				}
				var ids = jQuery("#sel_menu2").val();
				if (!ids) {
					swal("系统提示", "请至少选择一个成员进行添加操作", "warning");
					return false;
				}
				var userIds = "";
				if (ids.length > 0) {
					for (var i = 0; i < ids.length; i++) {
						userIds += ids[i] + ",";
					}
					userIds = userIds.substring(0, userIds.length - 1);
				}
				// console.log(ids);
				var url = basePath + "/sys/addRoleUser?ids=" + userIds + "&roleId=" + roleId;
				UN_COMMON.ajaxUrl(url, function(json) {
					if (json.success == true) {
						swal("系统提示", json.message, "success");
						// 刷新成员列表
						loadUserWithRole(roleId);
					} else {
						swal("系统提示", json.message, "error");
					}
				});
				e.stopPropagation();
			});

			$('.add-role').on('click', function() {
				$('#role_modal').data('isUpdate',false);
				$('#role_modal').modal('show');
			});

			//阻止表单action提交 采用ajax的方式提交数据
			$('#role_from').submit(function() {
				return false;
			});

			//表单验证
			$('#role_from').validate({
				errorElement : 'span',
				errorClass : 'help-block',
				focusInvalid : false,
				rules : {
					"roleName" : {
						required : true
					}
				},
				messages : {
					"roleName" : {
						required : "角色名称不能为空"
					}
				},
				highlight : function(element) {
					$(element).closest('.form-group').addClass('has-error');
				},
				success : function(label) {
					label.closest('.form-group').removeClass('has-error');
					label.remove();
				},
				errorPlacement : function(error, element) {
					element.parent('div').append(error);
				},
				//表单验证通过后的数据请求
				submitHandler : function(form) {
				    var isUpdate = $('#role_modal').data('isUpdate');
					var url =basePath+'/sys/addRole'
					if(isUpdate){
						url = basePath+'/sys/updateRole';
					}
					$.ajax({
						url : url,
						dataType : 'json',
						type : 'post',
						data : $('#role_from').serialize(),
						error : function() {
							$('#role_modal').modal('hide');
							swal("系统提示", '数据保存失败','error');
						},
						success : function(data) {
							$('#role_modal').modal('hide');
							if(data.success){
								loadRole();
							}
							swal("系统提示", data.message);
						}
					}) 

					return false;
				},
				invalidHandler : function(form, validator) { //不通过回调
					return false;
				}
			});

			$('#role_modal').on('show.bs.modal', function() {
				var isUpdate = $('#role_modal').data('isUpdate');
				$('#role_from')[0].reset();
				if(isUpdate){
					var roleId = $('#role_modal').data('roleid');
					loadRoleById(roleId);
				}
			});
			
			function loadRoleById(roleId){
				$.ajax({
					url:basePath+'/sys/loadRoleById?roleId='+roleId,
					dataType:'json',
					success:function(data){
						loadData(data);
						$('#role_from').append('<input type="hidden" name="roleId" value="'+data.roleId+'"><input type="hidden" name="created" value="'+data.created+'">');
					}
				});
			}
			
			/**
			 * 加载表单数据
			 * @param jsonStr
			 */
			function loadData(obj){
				var key,value,tagName,type,arr;
				for(x in obj){
					key = x;
					value = obj[x];
					
					$("[name='"+key+"'],[name='"+key+"[]']").each(function(){
						tagName = $(this)[0].tagName;
						type = $(this).attr('type');
						if(tagName=='INPUT'){
							if(type=='radio'){
								$(this).attr('checked',$(this).val()==value);
							}else if(type=='checkbox'){
								arr = value.split(',');
								for(var i =0;i<arr.length;i++){
									if($(this).val()==arr[i]){
										$(this).attr('checked',true);
										break;
									}
								}
							}else{
								$(this).val(value);
							}
						}else if(tagName=='SELECT' || tagName=='TEXTAREA'){
							$(this).val(value);
						}
						
					});
				}
			}
			
			loadRole();
			function loadRole(){
				$.ajax({
					url:basePath+'/sys/findAllRole',
					dataType:'json',
					success:function(data){
						refreshRoleView(data);
					}
				});
			}
			
			function refreshRoleView(roles){
				if(roles && roles.length>0){
					var html = "";
					for(var i = 0; i<roles.length; i++){
						html+='<li data-roleId="'+roles[i].roleId+'"><a href="javascript:;;">'+roles[i].roleName+' <span ';
						html+='class="pull-right"> <i class="fa fa-edit m-r-20" data-roleId="'+roles[i].roleId+'"></i><i';
						html+=' class="fa fa-trash-o" data-roleId="'+roles[i].roleId+'"></i></span></a></li>';
					}
					$('.role-list').html(html);
					initEvent();
				}else{
					$('.role-list').html('<div>暂无数据</div>');
				}
			}
			
			function initEvent(){
				$('.role-list li').on('click',function(){
					$('.role-list li').removeClass('active');
					$(this).addClass('active');
					var roleId = $(this).data('roleid');
					$('.nav-tabs a[href="#resource-role"]').data('roleId',roleId);
					//加载权限对应的用户列表
					//加载权限对应的资源列表
					loadUserWithRole(roleId);
					$("a.saveUserRoleBtn").data("roleid", roleId);
				});
				
				$('.role-list li .fa-edit').on('click',function(e){
					e.stopPropagation();
					$('#role_modal').data('isUpdate',true);
					var roleId = $(this).data('roleid');
					$('#role_modal').data('roleid',roleId);
					$('#role_modal').modal('show');
					
				});
				
				$('.role-list li .fa-trash-o').on('click',function(e){
					var roleId = $(this).data('roleid');
					swal({
	                    title: "您确定要删除这条角色信息吗",
	                    text: "删除后将无法恢复，请谨慎操作！",
	                    type: "warning",
	                    showCancelButton: true,
	                    confirmButtonColor: "#DD6B55",
	                    confirmButtonText: "删除",
	                    cancelButtonText:'取消',
	                    closeOnConfirm: false
	                }, function () {
	                	$.ajax({
	    					url:basePath+'/sys/deleteRoleById',
	    					dataType:'json',
	    					data:{
	    						roleId:roleId
	    					},
	    					success:function(data){
	    						if(data.success){
	    							loadRole();
	    						}
	    						swal("系统提示", data.message);
	    					}
	    				});
	                    
	                });
					
					e.stopPropagation();
				});
			}
			
			
			$('.nav-tabs a[href="#resource-role"]').on('click',function(){
				var roleId = $('.nav-tabs a[href="#resource-role"]').data('roleId');
				if(roleId){
					loadResourceWithRole(roleId);
				}else{
					swal("系统提示","请先选择一条角色信息");
				}
			});
			
			//加载权限对应的用户
			function loadUserWithRole(roleId){
				 $('#role_user_grid').DataTable().ajax.url(basePath+'/sys/findUserRoleWithRoleId?roleId='+roleId).load();
			}
			
			
			//加载权限对应的资源列表
			function loadResourceWithRole(roleId){
				$.ajax({
					url:basePath+'/sys/loadResourceWithRole?roleId='+roleId,
				    dataType:'json',
				    success:function(data){
				    	if(data.success){
				    		if(data.list && data.list.length>0){
				    			
				    			var templateHTML = $('#role_resourceTpl').html();
				    			var template = doT.template(templateHTML);
				    			var html = template(data.list, roleId);
				    			$('#resource-role section').html(html);
				    			$('.i-checks').iCheck({
				    				checkboxClass : 'icheckbox_square-green',
				    				radioClass : 'iradio_square-green',
				    			});
				    			
				    			var checkAll = $('input[name="all"]');
				    			var checkboxes = $('input[name="check"]');
				    			checkAll.on('ifChecked ifUnchecked', function(event) {
				    				if (event.type == 'ifChecked') {
				    					checkboxes.iCheck('check');
				    				} else {
				    					checkboxes.iCheck('uncheck');
				    				}
				    			});
				    			
				    			
				    			$('.saveResourceRoleBtn').on('click',function(){
				    				var str="";
				    				var ids="";
									var roleId = $('.nav-tabs a[href="#resource-role"]').data('roleId');
				    				$("input[name='check']:checkbox").each(function(){
				    					if(true == $(this).is(':checked')){
				    						str+=$(this).val()+",";
				    					}
				    				});
				    				if(str.substr(str.length-1)== ','){
				    					ids = str.substr(0,str.length-1);
				    				}
				    				
				    				if(ids && ids != ""){
				    					// 向服务器请求保存数据
										var url = basePath + "/sys/saveResourceRole?ids=" + ids + "&roleId=" +roleId;
										jQuery.ajax({
											url: url,
											cache: false,
											dataType: 'json',
											timeout: 4500,
											success: function (json, textStatus, jqXHR) {
												if (json.success) {
													swal("系统提示", json.message, "success");
												} else {
													swal("系统提示", json.message, "error");
												}
											},
											error: function (XMLHttpRequest, textStatus, errorThrown) {
												if (textStatus === 'error') {
													swal("系统提示", "无法进行操作！", "error");
												} else if (textStatus === 'timeout') {
													swal("系统提示", "连接超时，请检查网络是否正常！", "error");
												}
											}
										});
				    				}else{
				    					swal("系统提示","没有可保存的内容");
				    				}
				    			});
				    		}
				    	}
				    }
				});
			}
			
			var $roleUserTable = $('#role_user_grid').DataTable({
				"processing" : false,
				"serverSide" : true,
				"bLengthChange":false,
				"bFilter":true,
				"ordering": false,
				"ajax" : basePath+'/sys/findUserRoleWithRoleId?roleId=-1',
				"language" : {
					"url" : basePath+'/static/json/grid_language.json'
				},
				"columns" : [ {
	                 "sClass": "text-center",
	                 "data": "urId",
	                 "render": function (data, type, full, meta) {
	                     return '<input type="checkbox"  class="checkchild"  value="' + data + '" />';
	                 },
	                 "bSortable": false
	             },{
					"data": "userName"
				},{
					"data" : "deptName"
				},{
					"data" : "phone"
				},{
					"sClass": "text-center",
					"data" : "urId",
					"render": function (data, type, full, meta) {
	                     return '<button id="delete" data-urid="'+data+'" class="btn btn-danger btn-xs">移除</button>';
	                 }
				}]
			});
			
			$roleUserTable.on('click', '#delete', function (e) {
				var $this = jQuery(this);
				var urId= $this.data("urid");
				var url = basePath + "/sys/deleteUserRole?urId=" + urId;
				UN_COMMON.ajaxUrl(url, function (json) {
					if (json.success == true) {
						swal("系统提示", json.message, "success");
						var roleId = $('a.saveUserRoleBtn').data('roleid');
						loadUserWithRole(roleId);
					} else {
						swal("系统提示", json.message, "error");
					}
				});
			});
			
			$(".checkall").click(function () {
			      var check = $(this).prop("checked");
			      $(".checkchild").prop("checked", check);
			});
		});
	</script>
	
	<script id="role_resourceTpl" type="text/x-dot-template">
		<div class="row m-b-10">
			<label class="col-sm-2 control-label">角色权限明细</label>
			<div class="col-sm-2">
				<label class="checkbox-inline i-checks"> <input type="checkbox" name="all" >全选 
			</div>
		</div>
		{{for(var i=0;i<it.length;i++) { }}
		<div class="row m-b-10">
			<div class="col-sm-2">
				<label class="checkbox-inline i-checks"> 
				{{? it[i].checked }}
					<input type="checkbox" name="check" checked="checked" value="{{=it[i].menuId}}">{{=it[i].menuName}}</label>
				{{?? }}
					<input type="checkbox" name="check" value="{{=it[i].menuId}}">{{=it[i].menuName}}</label>
				{{? }} 
			</div>
			{{? it[i].childrenMenuRole }}
				<div class="col-sm-10">
					{{ for(var j=0; j<it[i].childrenMenuRole.length;j++) { }}
						<label class="checkbox-inline i-checks">
						{{? it[i].childrenMenuRole[j].checked}}
							<input type="checkbox" name="check" checked="checked" value="{{=it[i].childrenMenuRole[j].menuId}}">{{=it[i].childrenMenuRole[j].menuName}}</label>
						{{?? }}
							<input type="checkbox" name="check" value="{{=it[i].childrenMenuRole[j].menuId}}">{{=it[i].childrenMenuRole[j].menuName}}</label> 
						{{?}}
					{{ } }}
				</div>
			{{? }}
		</div>
		{{  } }}

		<div style="width:100%;text-align:center"><a href="javascript:void(0)" class="btn btn-warning saveResourceRoleBtn" style="width:120px;margin-top:30px;">保存</a></div>
	</script>
</body>
</html>